<script lang="tsx">
import { defineComponent, onMounted, ref, watch } from 'vue';
import { ElButton, ElMessage, ElMessageBox, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus';
import { $t } from '@vben/locales';
import { usePage } from '#/hooks/page/usePage';
import { Pencil, Send, Ban, Ellipsis, Trash2 } from '@vben/icons';
import deleteIcon from '#/assets/images/delete-icon.png';
import EditDrawer from './modules/track-mgr/edit-drawer.vue';
import JudgeSelector from './modules/track-mgr/judge-selector.vue';
import DimensionSelector from './modules/track-mgr/dimension-selector.vue';
import TrackDescriptionDrawer from './modules/track-mgr/track-description-drawer.vue';
import { getCompTrackPageApi, deleteCompTrackApi } from '#/api/competition/track-mgr';
import { getDictDataApi } from '#/api/system/dictData';
import { getCompGroupPageApi } from '#/api/competition/competitionCtgr';
import { updateCompTrackStatusApi } from '#/api/competition/track-mgr';
import { queryMatchListApi } from '#/api/competition/competition-list';
import dayjs from 'dayjs';
export default defineComponent({
  name: 'TrackMgrPage',
  setup() {
    const technosphereList = ref<any[]>([]);
    const competitionSelectList = ref<any[]>([]); // 大赛下拉列表
    const groupList = ref<any[]>([]);
    const defaultTechnosphereList = [
      {
        label: $t('trackMgr.industrialSoftwareInnovation'),
        value: '工业软件创新方向'
      },
      {
        label: $t('trackMgr.industrialSoftwareApplication'),
        value: '工业软件应用方向'
      },
      {
        label: 'CAD',
        value: 'CAD'
      },
      {
        label: 'CAE',
        value: 'CAE'
      },
      {
        label: 'CAM',
        value: 'CAM'
      },
      {
        label: 'CAPP',
        value: 'CAPP'
      },
      {
        label: 'MBSE',
        value: 'MBSE'
      },
      {
        label: 'AI',
        value: 'AI'
      },
    ]

    // 抽屉相关状态
    const showDrawer = ref(false);
    const drawerMode = ref<'add' | 'edit'>('add');
    const drawerFormData = ref<any>({}); // 抽屉表单数据

    // 设置评委对话框相关状态
    const showJudgeSelector = ref(false);
    const showDimensionSelector = ref(false);
    const currentTrackData = ref<any>({});

    // 赛题说明配置抽屉相关状态
    const showTrackDescriptionDrawer = ref(false);
    const trackDescriptionMode = ref<'add' | 'edit'>('add');
    const trackDescriptionFormData = ref<any>({});

    // 已选评委和维度ID
    const selectedJudgeIds = ref<(number | string)[]>([]);
    const selectedDimensionIds = ref<(number | string)[]>([]);

    // API配置
    const API = {
      get: getCompTrackPageApi,
    };

    // 表格列配置
    const columns = [
      { prop: 'name', label: $t('trackMgr.trackName'), minWidth: 150, showOverflowTooltip: true },
      { prop: 'technosphere', label: $t('trackMgr.technosphere'), minWidth: 150, showOverflowTooltip: true },
      { prop: 'compName', label: $t('trackMgr.belongCompetition'), minWidth: 300, showOverflowTooltip: true },
      { prop: 'groupName', label: $t('trackMgr.groupName'), minWidth: 100, showOverflowTooltip: true },
      { prop: 'belongMonth', label: $t('trackMgr.belongMonth'), minWidth: 100, showOverflowTooltip: true },
      {
        prop: 'releaseStatus', label: $t('trackMgr.status'), minWidth: 100, showOverflowTooltip: true,
        formatter: (row: any) => {
          const statusMap: any = {
            0: $t('trackMgr.unpublished'),
            1: $t('trackMgr.published'),
            2: $t('trackMgr.disabled'),
            3: $t('trackMgr.finished'),
          };
          const statusColors: any = {
            0: '#FB9A0E',
            1: '#30A46C',
            2: '#ccc',
            3: '#ccc',
          };
          return (
            <span style="display: flex; align-items: center;">
              <span
                style={{
                  display: 'inline-block',
                  width: '10px',
                  height: '10px',
                  borderRadius: '50%',
                  marginRight: '8px',
                  background: statusColors[row.releaseStatus] || '#ccc',
                }}
              ></span>
              {statusMap[row.releaseStatus] || row.releaseStatus || $t('announcement.unknown')}
            </span>
          );
        }
      },
      { prop: 'teamCount', label: $t('trackMgr.teamCount'), minWidth: 100, showOverflowTooltip: true },
      {
        prop: 'registrationStartTime', label: $t('trackMgr.registrationTime'), minWidth: 300, showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.registrationStartTime + $t('trackMgr.to') + row.registrationEndTime;
        }
      },
      {
        prop: 'createTime', label: $t('trackMgr.createTime'), minWidth: 180, showOverflowTooltip: true,
        formatter: (row: any) => {
          return dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss');
        }
      },
    ];

    // 操作按钮配置
    const commands = [
      {
        label: $t('trackMgr.edit'),
        key: 'edit',
        type: 'primary',
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={$t('common.editTxt')}
            show-after={600}
            placement="top"
          >
            <span class='operation-btn-wrapper'>
              <el-button icon={Pencil} link onClick={() => handleEdit(row)} disabled={row.releaseStatus == 2}></el-button>
              {row.draft && <span class="draft-dot"></span>}
            </span>
          </el-tooltip>
        )
      },
      {
        label: $t('trackMgr.publish'),
        key: 'publish', // 修复key重复问题
        type: 'primary',
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={row.releaseStatus == 0 || row.releaseStatus == 2 ? $t('trackMgr.publish') : $t('trackMgr.disable')}
            show-after={600}
            placement="top"
          >
            <span class='operation-btn-wrapper'>
              {(row.releaseStatus == 0 || row.releaseStatus == 2) && (
                <el-button icon={Send} link onClick={() => handleChangeStaus(row, 1)}></el-button>
              )}
              {(row.releaseStatus == 1 || row.releaseStatus == 3) && (
                <el-button icon={Ban} disabled={row.releaseStatus == 3} link onClick={() => handleChangeStaus(row, 2)}></el-button>
              )}
            </span>
          </el-tooltip>
        )
      },
      {
        key: 'delete',
        width: 40,
        label: $t('common.deleteTxt', ['']),
        icon: Trash2,
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={$t('common.deleteTxt', [''])}
            show-after={600}
            placement="top"
          >
            <span class='operation-btn-wrapper'>
              <el-button icon={Trash2} style={row.releaseStatus == 1 || row.releaseStatus == 3 ? { color: '#ccc' } : {}} link onClick={() => handleDelete(row)}></el-button>
            </span>
          </el-tooltip>
        )
      },
      {
        label: $t(''),
        key: 'more',
        type: 'primary',
        render: (row: any) => (
          <ElDropdown trigger="click">
            {{
              default: () => (
                <span class='operation-btn-wrapper relative top-[3px]'>
                  <ElButton icon={Ellipsis} link></ElButton>
                </span>
              ),
              dropdown: () => (
                <ElDropdownMenu>
                  <ElDropdownItem onClick={() => handleDropdownAction('addTrackDescription', row)}>
                    {row.trackDescStatus == 'create' ? $t('trackMgr.addTrackDescription') : $t('编辑赛题说明')}
                    {row.trackDescStatus === 'hasDraft' && <span class="relative w-[8px] h-[8px] top-[-5px] rounded-[50%] bg-[#ff3b30]"></span>}
                  </ElDropdownItem>
                  <ElDropdownItem onClick={() => handleDropdownAction('copyTrackDescriptionLink', row)}>
                    {$t('trackMgr.copyTrackDescriptionLink')}
                  </ElDropdownItem>
                  <ElDropdownItem onClick={() => handleDropdownAction('setJudges', row)}>
                    {row.expertJudgeList?.length > 0 ? $t('trackMgr.editJudgeSetting') : $t('trackMgr.addJudgeSetting')}
                  </ElDropdownItem>
                  <ElDropdownItem onClick={() => handleDropdownAction('setDimensions', row)}>
                    {row.reviewDimensionList?.length > 0 ? $t('trackMgr.editAssessmentRuleSetting') : $t('trackMgr.addAssessmentRuleSetting')}
                  </ElDropdownItem>
                </ElDropdownMenu>
              )
            }}
          </ElDropdown>
        )
      },
    ];

    // 删除配置
    const deleteProps = {
      title: $t('trackMgr.confirmDelete'),
      content: $t('trackMgr.confirmDeleteTrack'),
    };


    // 查询区配置
    const queryColumns = [
      { prop: 'name', label: $t('trackMgr.trackName'), type: 'input', placeholder: $t('common.inputPhTxt') },
      {
        prop: 'technosphere',
        label: $t('trackMgr.technicalField'),
        type: 'select',
        placeholder: $t('common.selectPhTxt'),
        options: technosphereList.value
      },
      {
        prop: 'compId',
        label: $t('trackMgr.belongCompetition'),
        type: 'select',
        placeholder: $t('common.selectPhTxt'),
        options: competitionSelectList.value,
      },
      {
        prop: 'compGroupId',
        label: $t('trackMgr.groupName'),
        type: 'select',
        placeholder: $t('common.selectPhTxt'),
        options: groupList.value
      },
      {
        prop: 'belongMonth',
        label: $t('trackMgr.belongMonth'),
        componentName: 'el-date-picker',
        type: 'month',
        placeholder: $t('common.selectPhTxt'),
        'value-format': 'YYYY-MM',  // 月份格式
        format: 'YYYY-MM',          // 显示格式
      },
      {
        prop: 'releaseStatus',
        label: $t('trackMgr.status'),
        type: 'select',
        placeholder: $t('common.selectPhTxt'),
        options: [
          {
            label: $t('trackMgr.unpublished'),
            value: 0,
          }, {
            label: $t('trackMgr.published'),
            value: 1,
          }, {
            label: $t('trackMgr.disabled'),
            value: 2,
          }, {
            label: $t('trackMgr.finished'),
            value: 3,
          }
        ]
      },

    ];

    // 使用页面表格hooks
    const {
      render,
      getTableData,
      queryState,
      tableState,
    } = usePage({
      operateProps: {
        fixed: 'right',
        width: '160px'
      },
      API,
      columns,
      queryColumns,
      commands,
      deleteProps,
    });

    // 处理大赛选择变化，根据大赛ID获取对应组别
    const handleCompetitionChange = async (compId: string) => {
      // 获取组别字段配置
      const groupColumn = queryState.columns.find((col: any) => col.prop === 'compGroupId');
      // 首先清空现有的组别选项和选中值
      groupList.value = [];
      delete queryState.data.compGroupId;
      if (groupColumn) {
        groupColumn.value = '';
        groupColumn.options = [];
      }
      // 如果没有选择大赛，直接返回
      if (!compId) {
        return;
      }
      try {
        const res = await getCompGroupPageApi({ compId });

        // 检查API响应是否包含有效数据
        if (res?.data?.length) {
          const newGroupOptions = res.data.map((item: any) => ({
            label: item.name,
            value: item.id,
          }));
          groupList.value = newGroupOptions;
          if (groupColumn) {
            groupColumn.options = newGroupOptions;
          }
        }
        // 如果没有数据，保持清空状态（已在开始时清空）
      } catch (error) { }
    };

    // 监听查询区配置中的大赛选项变化，根据大赛ID获取对应组别
    watch(() => queryState.data.compId, (newVal) => {
      handleCompetitionChange(newVal);
    }, {
      immediate: false,
      deep: true,
    });
    // 新增按钮事件
    const handleAdd = () => {
      drawerMode.value = 'add';
      drawerFormData.value = {
        name: '',
        technosphere: '',
        compId: '',
        compGroupId: '',
        compItemName: '',
        belongMonth: '',
        registrationTime: '',
        sort: '',
        intro: '',
      };
      showDrawer.value = true;
    };

    // 获取大赛下拉选项
    const getCompetitionSelectList = async () => {
      const res = await queryMatchListApi();
      const newCompetitionOptions = res.map((item: any) => {
        return {
          label: item.matchName,
          value: item.id
        }
      });
      competitionSelectList.value = newCompetitionOptions;

      // 更新查询区配置中的大赛选项
      const compColumn = queryState.columns.find((col: any) => col.prop === 'compId');
      if (compColumn) {
        compColumn.options = newCompetitionOptions;
      }
    };
    // 编辑按钮事件
    const handleEdit = (row: any) => {
      drawerMode.value = 'edit';
      // 传递完整的 row 数据，包括 draft 信息
      drawerFormData.value = {
        ...row,
        registrationTime: [row.registrationStartTime, row.registrationEndTime],
        // 保留原始的 draft 数据用于判断是否有草稿
        draft: row.draft
      };
      showDrawer.value = true;
    };

    // 删除按钮事件
    const handleChangeStaus = (row: any, type: number) => {
      // 发布
      if (type == 1) {
        updateCompTrackStatusApi({ id: row.id, releaseStatus: 1 }).then(() => {
          ElMessage.success($t('trackMgr.publishSuccessMsg'));
          getTableData();
        })
      } else {
        ElMessageBox({
          title: '',
          message: `
            <div style="display: flex; align-items: center;">
              <img src="${deleteIcon}" style="width: 48px; height: 48px; margin-right: 10px;" />
              <span>${$t('trackMgr.disableConfirm')}</span>
            </div>
          `,
          dangerouslyUseHTMLString: true,
          showCancelButton: true,
          confirmButtonText: $t('trackMgr.confirm'),
          cancelButtonText: $t('common.cancelTxt'),
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              updateCompTrackStatusApi({ id: row.id, releaseStatus: 2 }).then(() => {
                ElMessage.success($t('trackMgr.disableSuccess'));
                getTableData();
                instance.confirmButtonLoading = false
                done()
              })
            } else {
              done()
            }
          },
        })
      }
    };

    // 抽屉成功回调
    const handleDrawerSuccess = () => {
      showDrawer.value = false;
      getTableData(); // 刷新表格数据
    };

    // 抽屉点击取消
    const handleDrawerCancel = () => {
      showDrawer.value = false;
    };

    // 设置评委按钮事件
    const handleSetJudges = (row: any) => {
      currentTrackData.value = row;
      // 获取已选评委ID列表
      selectedJudgeIds.value = row.expertJudgeList || [];
      showJudgeSelector.value = true;
    };

    // 设置评审维度按钮事件
    const handleSetDimensions = (row: any) => {
      currentTrackData.value = row;
      // 获取已选评审维度ID列表
      selectedDimensionIds.value = row.reviewDimensionList || [];
      showDimensionSelector.value = true;
    };

    // 评委选择确认 - 子组件内部处理，这里只需要刷新数据
    const handleJudgeConfirm = () => {
      getTableData(); // 刷新表格数据
    };

    // 评审维度选择确认 - 子组件内部处理，这里只需要刷新数据
    const handleDimensionConfirm = () => {
      getTableData(); // 刷新表格数据
    };

    // 删除草稿后的刷新事件 - 优化为只更新当前行数据
    const handleDeleteDraft = () => {
      // 更新当前编辑行的数据，移除draft字段
      if (drawerFormData.value && drawerFormData.value.id) {
        // 清除草稿数据
        drawerFormData.value.draft = null;

        // 更新表格中对应行的数据，移除draft字段
        const targetRowId = drawerFormData.value.id;
        const tableData = tableState.data as any[];

        // 找到对应的行并更新draft字段
        const targetRowIndex = tableData.findIndex((row: any) => row.id === targetRowId);
        if (targetRowIndex !== -1 && tableData[targetRowIndex]) {
          // 直接修改表格数据中的draft字段，这样编辑按钮上的圆点会立即消失
          (tableData[targetRowIndex] as any).draft = null;
        }
      }
    };

    const handleDelete = (row: any) => {
      if (row.releaseStatus == 1) {
        ElMessage.warning($t('已发布数据不可删除！'));
        return;
      } else if (row.releaseStatus == 3) {
        ElMessage.warning($t('已结束数据不可删除！'));
        return;
      }
      ElMessageBox({
        title: '',
        message: `
          <div style="display: flex; align-items: center;">
            <img src="${deleteIcon}" style="width: 48px; height: 48px; margin-right: 10px;" />
            <span>${$t('trackMgr.dataDeleteConfirm')}</span>
          </div>
        `,
        dangerouslyUseHTMLString: true,
        showCancelButton: true,
        confirmButtonText: $t('trackMgr.confirm'),
        cancelButtonText: $t('common.cancelTxt'),
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteCompTrackApi({ id: row.id }).then(() => {
              ElMessage.success($t('trackMgr.deleteSuccessMsg'));
              getTableData();
              instance.confirmButtonLoading = false
              done()
            }).finally(() => {
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        },
      })
    };

    const getTechnosphereList = async () => {
      technosphereList.value = [...defaultTechnosphereList];
      const techColumn = queryState.columns.find((col: any) => col.prop === 'technosphere');
      if (techColumn) {
        techColumn.options = [...defaultTechnosphereList];
      }
      getDictDataApi({ dictCode: 'technosphere' }).then(res => {
        if (res?.length) {
          const newTechnosphereOptions = res.map((item: any) => {
            let obj = {
              label: item.dictDataValue,
              value: item.dictDataValue,
            }
            return obj;
          });
          technosphereList.value = [...defaultTechnosphereList, ...newTechnosphereOptions];
          // 更新查询区配置中的技术领域选项
          if (techColumn) {
            techColumn.options = [...defaultTechnosphereList, ...newTechnosphereOptions];
          }
        }
      })
    };

    onMounted(() => {
      getTechnosphereList();
      getCompetitionSelectList();
    });

    // 新增赛题说明配置
    const handleAddTrackDescription = (row: any) => {
      trackDescriptionMode.value = 'edit'; // 基于现有赛题进行配置
      trackDescriptionFormData.value = { ...row };
      showTrackDescriptionDrawer.value = true;
    };

    // 复制赛题说明链接
    const handleCopyTrackDescriptionLink = (row: any) => {
      // TODO: 实现复制链接功能
      console.log('复制赛题说明链接:', row);
      ElMessage.info($t('trackMgr.copyLinkFeatureComingSoon'));
    };

    // 赛题说明配置成功回调
    const handleTrackDescriptionSuccess = () => {
      showTrackDescriptionDrawer.value = false;
      getTableData(); // 刷新表格数据
    };

    // 赛题说明配置取消回调
    const handleTrackDescriptionCancel = () => {
      showTrackDescriptionDrawer.value = false;
    };

    const handleDropdownAction = (action: string, row: any) => {
      switch (action) {
        case 'addTrackDescription':
          handleAddTrackDescription(row);
          break;
        case 'copyTrackDescriptionLink':
          handleCopyTrackDescriptionLink(row);
          break;
        case 'setJudges':
          handleSetJudges(row);
          break;
        case 'setDimensions':
          handleSetDimensions(row);
          break;
        default:
          break;
      }
    };

    return () => (
      <div>
        {render({
          header: (
            <ElButton type="primary" onClick={handleAdd}>
              {$t('trackMgr.add')}
            </ElButton>
          ),
        })}
        <EditDrawer
          modelValue={showDrawer.value}
          formData={drawerFormData.value}
          mode={drawerMode.value}
          onUpdate:modelValue={val => showDrawer.value = val}
          technosphereList={technosphereList.value}
          onSuccess={handleDrawerSuccess}
          onCancel={handleDrawerCancel}
          onDraftDeleted={handleDeleteDraft}
        />
        <JudgeSelector
          modelValue={showJudgeSelector.value}
          trackId={currentTrackData.value.id}
          selectedJudgeIds={selectedJudgeIds.value}
          mode={selectedJudgeIds.value.length > 0 ? 'edit' : 'add'}
          onUpdate:modelValue={val => showJudgeSelector.value = val}
          onConfirm={handleJudgeConfirm}
          onCancel={() => showJudgeSelector.value = false}
        />
        <DimensionSelector
          modelValue={showDimensionSelector.value}
          trackId={currentTrackData.value.id}
          selectedDimensionIds={selectedDimensionIds.value}
          mode={selectedDimensionIds.value.length > 0 ? 'edit' : 'add'}
          onUpdate:modelValue={val => showDimensionSelector.value = val}
          onConfirm={handleDimensionConfirm}
          onCancel={() => showDimensionSelector.value = false}
        />
        <TrackDescriptionDrawer
          modelValue={showTrackDescriptionDrawer.value}
          formData={trackDescriptionFormData.value}
          mode={trackDescriptionMode.value}
          onUpdate:modelValue={(val: boolean) => showTrackDescriptionDrawer.value = val}
          onSuccess={handleTrackDescriptionSuccess}
          onCancel={handleTrackDescriptionCancel}
        />
      </div>
    );
  }
});
</script>
<style scoped>
:deep(.operation-btn-wrapper) {
  position: relative;
  display: inline-block;
  /* 改为最小宽度，避免内容被截断 */
  min-width: 32px;
  text-align: center;

  .draft-dot {
    position: absolute;
    top: 4px;
    right: 8px;
    width: 8px;
    height: 8px;
    background: #ff3b30;
    border-radius: 50%;
    z-index: 1;
  }
}

/* 确保操作列有足够的宽度 */
:deep(.el-table__fixed-right) {
  .el-table__cell {
    /* 根据实际操作按钮数量调整 */
    width: 100px;
  }
}

:deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
  width: 100%;
}
</style>
